# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import touchDriver as Tdriver
import time
from machine import Timer
import urandom

#实始化一个点击器控制实例对象
tobj = Tdriver.TouchObj()

isRUN = False
isTimerEnd = False
tim = Timer(-1)  #新建一个虚拟定时器

def randint(min, max):
    span = max - min + 1
    div = 0x3fffffff // span
    offset = urandom.getrandbits(30) // div
    val = min + offset
    # val =  random.randint(min, max)
    return val

def stopTimer():
    global isRUN,isTimerEnd
    tim.deinit()          #循环次数到了，程序结束
    setAllPinStates(0b1111111111111111)
    isRUN = False
    isTimerEnd = True

def checkKey():
    tkey = tobj.key.value()
    if not tkey:
        stopTimer()

timer2count = -1

def delayTimer(t):
    global isTimerEnd,timer2count
    timer2count -= 100
    if timer2count <= 0:
        t.deinit()
        isTimerEnd = True
    elif timer2count >= 100:
        t.init(period=100,mode=Timer.ONE_SHOT ,callback=delayTimer)
    else:
        t.init(period=timer2count,mode=Timer.ONE_SHOT ,callback=delayTimer)
    print(timer2count)
    checkKey()

def delay(ms):
    global timer2count,isTimerEnd  
    isTimerEnd = False
    timer2count = ms
    tim.init(period=100,mode=Timer.ONE_SHOT ,callback=delayTimer)
    while not isTimerEnd:
        time.sleep_ms(10)
    return (not isRUN)

#pNumber按键按下,pNumber从0~15
def touchPin(pNumber):
    tobj.setPin(pNumber,False)
    tobj.updateData()
#pNumber按键抬起,pNumber从0~15
def unTouchPin(pNumber):
    tobj.setPin(pNumber,True)
    tobj.updateData()
#按下并抬起,即点按一次
def touchOncePin(pNumber):
    touchPin(pNumber)
    time.sleep_ms(100)  #按下时间为50毫秒
    unTouchPin(pNumber)
    time.sleep_ms(100)  #抬起后再等50毫秒

def touchPinTimes(p,n,dt1 = 800,dt2 = 1500):
    
    for i in range(n):
        touchOncePin(p)
        dt = randint(dt1,dt2)
        if delay(dt):
            return True
    return False


#使用16位的按键状态数一次控制所有点击头状态
def setAllPinStates(state):
    tobj.set16Pins(state)
    tobj.updateData()


allUntouch = 0b1111111111111111    #所有点击头抬起
danshu     = 0b1010101010101010    #单数按下
shuanshu   = 0b0101010101010101    #双数按下


#t按下一次按键程序运行多少次
baseTimes = -2

#这里运行点击逻辑
def touchLoop():    
    print('touch0')
    if touchPinTimes(0,5,800,1200):
        return
    print('touch1')
    if touchPinTimes(1,5,800,1200):
        return
    dt = randint(40000,45000)
    print('delay=%.2fs',dt/1000)
    if delay(dt):
        return
    print('touch2')
    touchOncePin(2)
    dt = randint(2000,2500)
    if delay(dt):
        return
    touchOncePin(3)
    print('delay=5s')
    if delay(5000):
        return
def main():
    global isRUN
    setAllPinStates(0b1111111111111111)
    runCount = baseTimes
    #按键检测循环
    while True:
        if isRUN:
            if runCount < -1:
                touchLoop()
            elif runCount > 0:
                runCount -= 1
                touchLoop()
            elif runCount == 0:
                stopTimer()
                runCount = baseTimes
            time.sleep(1)
        else:
            tkey = tobj.key.value()
            if not tkey:
                isRUN = True
                time.sleep(1)
        time.sleep_ms(50)

    
if __name__ == '__main__':  
    main()
    